#include "XIntermediarySubscriber.h"

namespace Xts
{
	namespace IceRuntime 
	{
		XIntermediarySubscriber::XIntermediarySubscriber(const Ice::CommunicatorPtr& pIc, const Ice::LoggerPtr& pLogger)
			:XStormBase(pIc, pLogger)
		{
		}

		XIntermediarySubscriber::~XIntermediarySubscriber(void)
		{
		}

		bool XIntermediarySubscriber::Subscribe(const std::string& topicName, const std::string& monitorDsb)
		{
			IceStorm::TopicPrx topicPrx = RetrieveTopic(topicName);
			if(topicPrx == NULL)
			{
				x_pLogger->error(topicName + " can't be retrieved");
				return false;
			}

			try
			{
				Ice::ObjectPrx subPrx = x_pIc->stringToProxy(monitorDsb);
				topicPrx->subscribeAndGetPublisher(x_qos, subPrx);
				return true;
			}
			catch(const ::IceStorm::AlreadySubscribed)
			{
				x_pLogger->error(topicName + ": Already Subscribed.");
			}
			catch(const Ice::Exception& ex)
			{
				x_pLogger->error(ex.what());		
			}
			return false;
		}

		bool XIntermediarySubscriber::Unsubscribe(const std::string& topicName, const std::string& monitorDsb)
		{
			/*if(!IsTopicManagerValid())
			{
				x_pLogger->error("Topic Manager is not initialized. Can't subscribe topic.");
				return false;
			}*/

			IceStorm::TopicPrx topicPrx = RetrieveTopic(topicName);		
			if(topicPrx == NULL)
			{
				x_pLogger->error(topicName + " can't be retrieved");
				return false;
			}

			try
			{
				//topicPrx = x_topicManagerPrx->retrieve(topicName);
				Ice::ObjectPrx subPrx = x_pIc->stringToProxy(monitorDsb);
				topicPrx->unsubscribe(subPrx);
				return true;
			}
			catch (const ::IceStorm::NoSuchTopic&)
			{
				x_pLogger->error(topicName + " is not exist. Can't unsubscribe.");
			}
			catch(const Ice::Exception& ex)
			{
				x_pLogger->error(ex.what());		
			}
			return false;
		}

		bool XIntermediarySubscriber::RetrievePublishPrx(const ::std::string& topicName, ::Ice::ObjectPrx& publisherPrx)
		{
			::IceStorm::TopicPrx topic = RetrieveTopic(topicName);

			if(topic == NULL)
			{
				x_pLogger->error("Failed to retrieve topic:" + topicName);
				return false;
			}

			try
			{
				publisherPrx = topic->getPublisher();
				return true;
			}			
			catch (const ::Ice::Exception& ex)
			{
				x_pLogger->error(ex.what());
			}
			return false;
		}
	}
}